package com.hsp.homework.test03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @Author Stringzhua
 * @Date 2024/4/10 17:39
 * description:文件下载客户端
 */
public class Client {
    public static void main(String[] args) throws Exception {
        //1.接收用户输入,指定下载文件名
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载文件名:");
        String downloadFileName = scanner.next();

        //2.客户端连接服务端,准备发送
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //3.获取和socket关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(downloadFileName.getBytes());
        //设置写入结束的标志
        socket.shutdownOutput();

        //4.读取服务器端返回的文件(字节数组)
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //5.使用工具类StreamUtils,读取文件到一个字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //6.得到一个输出流,准备将bytes上的内容写入到磁盘文件
        //下载的是高山流水=>下载的就是高山流水.mp3
        //下载的是爪爪=>下载的就是无名.mp3 文件名是爪爪.mp3
        String filePath = "E:\\qiyeke\\filecontroller\\music\\" + downloadFileName + ".mp3";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(bytes);

        //7.关闭相关的资源
        bos.close();
        bis.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端下载完毕,正确退出");
    }
}
